<template>
  <div class="contract-approval route-page" :class="isMobile ? 'isMobile' : ''">
    <section class="header" v-if="!errMsg">
      <!-- @back="goBack" -->
      <a-page-header :class="notBack ? 'hide-back' : ''" :title="headerInfo.title" @back="goBack">
        <template #tags>
          <a-tag :color="headerInfo.statusColor">
            {{ headerInfo.statusTxt }}
          </a-tag>
        </template>
        <template #extra v-if="headerInfo.btns && headerInfo.btns.length">
          <!-- /审批通过/审批拒绝/关闭申请/关闭申请+删除/再次申请/查看原合同/查看新合同 -->
          <!-- $buttonData = ['PASS', 'REFUSE', 'CLOSE', 'CLOSE_DEL', 'AGAIN', 'LOOK_ORIGINAL','LOOK_NEW']; -->
          <a-space>
            <a-button
              type="primary"
              key="PASS"
              v-if="headerInfo.btns.includes('PASS')"
              @click="topBtnClick('PASS')"
            >
              审批通过
            </a-button>
            <a-button
              type="primary"
              key="AGAIN"
              ghost
              v-if="headerInfo.btns.includes('AGAIN')"
              @click="topBtnClick('AGAIN')"
            >
              再次申请
            </a-button>
            <a-button
              type="primary"
              danger
              key="REFUSE"
              v-if="headerInfo.btns.includes('REFUSE')"
              @click="topBtnClick('REFUSE')"
            >
              审批拒绝
            </a-button>
            <a-button
              key="LOOK_ORIGINAL"
              v-if="headerInfo.btns.includes('LOOK_ORIGINAL')"
              @click="topBtnClick('LOOK_ORIGINAL')"
            >
              查看原合同
            </a-button>
            <a-button
              key="LOOK_NEW"
              v-if="headerInfo.btns.includes('LOOK_NEW')"
              @click="topBtnClick('LOOK_NEW')"
            >
              查看新合同
            </a-button>
            <a-button
              key="CLOSE"
              v-if="headerInfo.btns.includes('CLOSE')"
              @click="topBtnClick('CLOSE')"
            >
              关闭申请
            </a-button>
            <a-button
              key="CLOSE_DEL"
              v-if="headerInfo.btns.includes('CLOSE_DEL')"
              @click="topBtnClick('CLOSE_DEL')"
            >
              关闭申请&删除合同
            </a-button>
          </a-space>
        </template>
      </a-page-header>
    </section>
    <section
      class="content"
      :class="headerInfo.btns && headerInfo.btns.length ? 'hasHandleBtn' : ''"
      v-if="!errMsg"
    >
      <section class="left" v-show="!isMobile">
        <a-anchor
          @click="(e) => e.preventDefault()"
          :getContainer="() => contentRef"
        >
          <a-anchor-link href="#approvalBasicInfo" title="基本信息" />
          <a-anchor-link href="#approvalContent" title="审批内容" />
          <a-anchor-link href="#approvalCurrentStep" title="当前审批流程" />
          <a-anchor-link href="#approvalHistory" title="历史审批流程" />
        </a-anchor>
      </section>
      <section class="right">
        <div class="right-content" ref="contentRef">
          <section id="approvalBasicInfo">
            <a-card title="基本信息" v-if="approvalDetail.mainInfo">
              <a-descriptions
                :column="descCols"
                layout="vertical"
                :labelStyle="labelStyle"
                :contentStyle="contentStyle"
              >
                <a-descriptions-item label="审批类型">
                  {{ approvalDetail.mainInfo.process_type_txt }}
                </a-descriptions-item>
                <a-descriptions-item label="业务类型">
                  {{ approvalDetail.mainInfo.work_type_txt }}
                </a-descriptions-item>
                <a-descriptions-item label="提交人">
                <span
                  class="link"
                  @click="showUserInfo(approvalDetail.mainInfo, 'cuser_uid')"
                >
                  {{ approvalDetail.mainInfo.cuser_name }}
                </span>
                </a-descriptions-item>
                <a-descriptions-item label="发起时间">
                  {{ approvalDetail.mainInfo.launch_time }}
                </a-descriptions-item>
                <a-descriptions-item label="审批状态">
                  {{ approvalDetail.mainInfo.status_txt }}
                </a-descriptions-item>
              </a-descriptions>
            </a-card>
          </section>
          <section id="approvalContent" class="mt-20">
            <a-card title="审批内容">
              <template #extra>
                <a-button
                  type="link"
                  @click="checkContractDetail"
                  v-if="!contractNotFound"
                >
                  查看合同详情
                </a-button>
              </template>
              <a-card-grid style="width: 100%">
                <a-descriptions
                  v-if="isCanceled"
                  :column="descCols"
                  title="作废信息"
                  layout="vertical"
                  :labelStyle="labelStyle"
                  :contentStyle="contentStyle"
                >
                  <a-descriptions-item label="租客名称">
                    {{ contractDetail.owner_name }}
                  </a-descriptions-item>
                  <a-descriptions-item label="合同编号">
                    {{ contractDetail.contract_number }}
                  </a-descriptions-item>
                  <a-descriptions-item label="经办人">
                    {{ contractDetail.followup_uname }}
                  </a-descriptions-item>
                  <a-descriptions-item label="合同租赁数">
                    {{
                      contractDetail.lease_area +
                      (contractDetail.lease_square_unit || "㎡")
                    }}
                  </a-descriptions-item>
                  <!-- <a-descriptions-item label="楼宇名称">
                    {{ buildingInfo.buildName }}
                  </a-descriptions-item> -->
                  <a-descriptions-item label="楼宇-楼层-房号">
                    <a-tooltip>
                      <template #title>
                        {{ buildingInfo.roomNo }}
                      </template>
                      <div
                        class="nowrap"
                        :class="{
                        link:
                          buildingInfo.roomNoArr &&
                          buildingInfo.roomNoArr.length == 1,
                      }"
                        @click="roomDetail()"
                      >
                        {{ buildingInfo.roomNo }}
                      </div>
                    </a-tooltip>
                  </a-descriptions-item>
                  <a-descriptions-item label="作废发起人">
                    {{ cancelInfo.operate_user }}
                  </a-descriptions-item>
                  <a-descriptions-item
                    label="作废原因"
                    v-if="cancelInfo.operate_content"
                  >
                    {{ cancelInfo.operate_content.content }}
                  </a-descriptions-item>
                </a-descriptions>
                <a-descriptions
                  v-else-if="contractDetail.status == 5"
                  :column="descCols"
                  title="合同退租信息"
                  layout="vertical"
                  :labelStyle="labelStyle"
                  :contentStyle="contentStyle"
                >
                  <a-descriptions-item label="租客名称">
                    {{ contractDetail.owner_name }}
                  </a-descriptions-item>
                  <a-descriptions-item label="合同编号">
                    {{ contractDetail.contract_number }}
                  </a-descriptions-item>
                  <a-descriptions-item label="退租类型">{{
                      retreatInfo.retreat_type_txt
                    }}</a-descriptions-item>
                  <a-descriptions-item label="退租日期">{{
                      dateFormat(retreatInfo.retreat_date)
                    }}</a-descriptions-item>
                  <a-descriptions-item label="合同签订日">
                    {{ contractDetail.sign_time }}
                  </a-descriptions-item>
                  <a-descriptions-item label="工商注册地址变更日期"
                  >{{ dateFormat(retreatInfo.bcc_change_date) }}
                  </a-descriptions-item>
                  <!-- <a-descriptions-item label="楼宇名称">
                    {{ buildingInfo.buildName }}
                  </a-descriptions-item> -->
                  <a-descriptions-item label="楼宇-楼层-房号">
                    <a-tooltip>
                      <template #title>
                        {{ buildingInfo.roomNo }}
                      </template>
                      <div
                        class="nowrap"
                        :class="{
                        link:
                          buildingInfo.roomNoArr &&
                          buildingInfo.roomNoArr.length == 1,
                      }"
                        @click="roomDetail()"
                      >
                        {{ buildingInfo.roomNo }}
                      </div>
                    </a-tooltip>
                  </a-descriptions-item>
                  <a-descriptions-item label="退租原因">
                    <template
                      v-if="
                      retreatInfo.retreat_reason_txt &&
                      retreatInfo.retreat_reason_txt.length > 0
                    "
                    >
                    <span
                      v-for="item in retreatInfo.retreat_reason_txt"
                      :key="item"
                    >{{ item + "," }}
                    </span>
                    </template>
                  </a-descriptions-item>
                </a-descriptions>
                <template v-else>
                  <div
                    v-if="contractNotFound"
                    style="
                    width: 100%;
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                  "
                  >
                    <img
                      :src="
                      $utils.staticPath +
                      'images/contract/contract_not_found.jpg'
                    "
                      alt=""
                      style="width: 200px; height: 200px"
                    />
                    <span style="font-size: 16px; margin-bottom: 20px">
                    未找到合同信息
                  </span>
                  </div>
                  <a-descriptions
                    v-else
                    :column="descCols"
                    title="合同基本信息"
                    layout="vertical"
                    :labelStyle="labelStyle"
                    :contentStyle="contentStyle"
                  >
                    <a-descriptions-item label="租客名称">
                      {{ contractDetail.owner_name }}
                    </a-descriptions-item>
                    <a-descriptions-item label="合同编号">
                      {{ contractDetail.contract_number }}
                    </a-descriptions-item>
                    <a-descriptions-item label="经办人">
                    <span
                      class="link"
                      @click="showUserInfo(contractDetail, 'followup_uid')"
                    >
                      {{ contractDetail.followup_uname }}
                    </span>
                    </a-descriptions-item>
                    <a-descriptions-item label="合同租赁数">
                      {{
                        contractDetail.lease_area +
                        (contractDetail.lease_square_unit || "㎡")
                      }}
                    </a-descriptions-item>
                    <a-descriptions-item label="合同签订日">
                      {{ contractDetail.sign_time }}
                    </a-descriptions-item>
                    <a-descriptions-item label="合同开始日">
                      {{ contractDetail.lease_starttime }}
                    </a-descriptions-item>
                    <a-descriptions-item label="合同结束日">
                      {{ contractDetail.lease_endtime }}
                    </a-descriptions-item>
                    <a-descriptions-item label="楼宇-楼层-房号">
                      <a-tooltip>
                        <template #title>
                          {{ buildingInfo.roomNo }}
                        </template>
                        <div
                          class="nowrap"
                          :class="{
                          link:
                            buildingInfo.roomNoArr &&
                            buildingInfo.roomNoArr.length == 1,
                        }"
                          @click="roomDetail()"
                        >
                          {{ buildingInfo.roomNo }}
                        </div>
                      </a-tooltip>
                    </a-descriptions-item>
                    <a-descriptions-item
                      label="滞纳金比例"
                      v-if="contractDetail.late_fee"
                    >
                      {{ contractDetail.late_fee.ratio || "--" }}
                    </a-descriptions-item>
                  </a-descriptions>
                </template>
              </a-card-grid>
              <template
                v-if="
                contractDetail.status == 5 ||
                contractDetail.status == 6 ||
                contractDetail.status == 7
              "
              >
                <a-card-grid style="width: 100%" class="bill-card">
                  <div class="ant-descriptions-title" style="margin-bottom: 10px">
                    账单结算
                  </div>
                  <a-table
                    :columns="billColumns"
                    :data-source="billTableData"
                    :pagination="false"
                    rowKey="id"
                    :scroll="{ x: 'max-content', y: 270 }"
                  >
                    <template #bodyCell="{ text, record, index, column }">
                      <template v-if="column.key === 'actual_retreat'">
                        <a-tag color="green" v-if="record.pay_type == 'income'"
                        >收</a-tag
                        >
                        <a-tag color="orange" v-else>付</a-tag>
                        <span>{{record.actual_retreat}}</span>
                        <span class="text-primary">{{`(修改前 ￥${record.before_amount || 0})`}}</span>
                      </template>
                      <template v-if="column.key === 'carry_over'">
                        <a-tag color="green">入</a-tag>￥{{ record.into_amount || 0 }}
                        <span v-if="record.out_amount">
                    <a-tag color="red" style="margin-left: 8px">出</a-tag>￥{{ record.out_amount || 0 }}
                  </span>
                        <span v-if="record.into_amount || record.out_amount" style="margin-left: 4px; font-size: 12px" class="link" @click="viewCarryOver(record)">
                    查看
                  </span>
                      </template>
                      <template v-if="column.key === 'bill_number'">
                        <span :class="text ? 'link' : ''" @click.stop="viewBillDetail(record.id)">{{text || '--'}}</span>
                      </template>
                    </template>
                  </a-table>
                  <a-alert
                    :message="billTotalStatus + Math.abs(billTotal).toFixed(2) + '元'"
                    type="info"
                  />
                </a-card-grid>
                <a-card-grid style="width: 100%" class="bill-card">
                  <div class="ant-descriptions-title" style="margin-bottom: 10px">
                    保证金
                  </div>
                  <a-table
                    :columns="bondColumns"
                    :data-source="bondTableData"
                    :pagination="false"
                    rowKey="id"
                    :scroll="{  x: 'max-content', y: 270 }"
                  >
                    <template #bodyCell="{ text, record, index, column }">
                      <template v-if="column.key === 'carry_over'">
                        <a-tag color="green">入</a-tag>￥{{ record.into_amount || 0 }}
                        <span v-if="record.out_amount">
                    <a-tag color="red" style="margin-left: 8px">出</a-tag>￥{{ record.out_amount || 0 }}
                  </span>
                        <span v-if="record.into_amount || record.out_amount" style="margin-left: 4px; font-size: 12px" class="link" @click="viewCarryOver(record)">
                    查看
                  </span>
                      </template>
                      <template v-if="column.key === 'bill_number'">
                        <span :class="text ? 'link' : ''" @click.stop="viewBillDetail(record.id)">{{text || '--'}}</span>
                      </template>
                      <template v-if="column.key === 'forfeit_amount'">
                        <span>{{text || '--'}}</span>
                        <span v-if="text > 0" class="link" style="margin-left: 6px" @click="viewForfeit(record)">
                    查看记录
                  </span>
                      </template>
                    </template>
                  </a-table>
                  <a-alert
                    :message="bondTotalStatus + Math.abs(bondTotal).toFixed(2) + '元'"
                    type="info"
                  />
                </a-card-grid>
                <a-card-grid style="width: 100%" class="bill-card">
                  <div class="ant-descriptions-title" style="margin-bottom: 10px">
                    预存费用
                  </div>
                  <a-table
                    :columns="prestoreColumns"
                    :data-source="prestoreData"
                    :pagination="false"
                    rowKey="id"
                    :scroll="{ y: 270 }"
                  >
                    <template #bodyCell="{ text, record, index, column }">
                      <template v-if="column.key == 'actual_retreat'">
                        <span>{{record.actual_retreat}}</span>
                        <span class="text-primary">{{`(修改前 ￥${record.before_amount || 0})`}}</span>
                      </template>
                    </template>
                  </a-table>
                  <a-alert
                    :message="'合计需付：' + Math.abs(prestoreTotal).toFixed(2) + '元'"
                    type="info"
                  />
                </a-card-grid>
              </template>

              <a-card-grid style="width: 100%" class="bill-card" v-if="contractDetail.op_type == 5 && purposeData?.length">
                <div class="ant-descriptions-title" style="margin-bottom: 10px">
                  {{purposeData[0]?.cost_type_txt || '保证金'}}
                </div>
                <a-table
                  :columns="purposeColumns"
                  :data-source="purposeData"
                  :loading="purposeLoading"
                  :pagination="false"
                  rowKey="bill_id"
                >
                  <template #bodyCell="{ text, record, index, column }">
                    <template v-if="column.key === 'carry_over'">
                      <a-tag color="green">入</a-tag>￥{{ record.into_amount || 0 }}
                      <span v-if="record.out_amount">
                     <a-tag color="red" style="margin-left: 8px">出</a-tag>￥{{ record.out_amount || 0 }}
                  </span>
                    </template>
                  </template>
                </a-table>
                <a-alert
                  :message="'合计应退' + Math.abs(purposeTotal).toFixed(2) + '元'"
                  type="info"
                />
              </a-card-grid>

              <a-card-grid
                style="width: 100%; padding: 0px"
                v-if="contractDetail.id"
              >
                <attachment-info
                  :active="getAttach"
                  :params="attachParams"
                  :showOption="false"
                />
              </a-card-grid>
            </a-card>
          </section>
          <!-- 条款信息 -->
          <section
            id="contractClause"
            style="margin-top: 20px"
            v-if="contractDetail.clauseData && contractDetail.clauseData.length"
          >
            <a-card title="条款信息">
              <a-card-grid
                style="width: 100%"
                v-for="(clause, clauseIndex) of contractDetail.clauseData"
                :key="clause.id"
              >
                <a-descriptions
                  :column="descCols"
                  :title="clauseIndex + 1 + '.' + clause.clause_name"
                  layout="vertical"
                  :labelStyle="labelStyle"
                  :contentStyle="contentStyle"
                >
                </a-descriptions>
                <a-row :gutter="12">
                  <a-col :span="14">
                    <a-descriptions
                      :column="4"
                      layout="vertical"
                      :labelStyle="labelStyle"
                      :contentStyle="contentStyle"
                    >
                      <template #title>
                        <div class="text-title">基本条款</div>
                      </template>
                      <a-descriptions-item label="房源信息">
                        <a-tooltip>
                          <template #title>
                            {{ getClauseCheckedBuild(clause.checked_build) }}
                          </template>
                          <div
                            class="nowrap"
                            :class="{
                            link:
                              clause.checked_build &&
                              clause.checked_build.room &&
                              clause.checked_build.room.length == 1,
                          }"
                            @click="roomDetail(clause.checked_build)"
                          >
                            {{ getClauseCheckedBuild(clause.checked_build) }}
                          </div>
                        </a-tooltip>
                      </a-descriptions-item>
                      <a-descriptions-item label="租赁数">
                        {{ clause.basic_clause.lease_area || "--" }}
                        {{ clause.basic_clause.lease_square_unit }}
                      </a-descriptions-item>
                      <template v-if="clause.tax_clause">
                        <a-descriptions-item label="含税规则">
                          {{ clause.tax_clause.taxRuleTxt }}
                        </a-descriptions-item>
                        <a-descriptions-item label="税率" >
                          {{clause?.tax_clause?.taxRateTxt || "--"}}
                        </a-descriptions-item>
                      </template>
                    </a-descriptions>
                  </a-col>
                  <a-col
                    :span="10"
                    style="border-left: 1px solid #f4f4f4; padding-left: 30px"
                  >
                    <a-descriptions
                      :column="2"
                      layout="vertical"
                      :labelStyle="labelStyle"
                      :contentStyle="contentStyle"
                    >
                      <template #title>
                        <div class="text-title">保证金条款</div>
                      </template>
                      <a-descriptions-item label="保证金类型">
                        {{ clause?.bond_clause?.bond_type_txt || "--" }}
                      </a-descriptions-item>
                      <a-descriptions-item label="保证金金额">
                        {{ clause?.bond_clause?.bond_price || "--" }}
                        {{ clause?.bond_clause?.bond_unit_txt || "" }}
                      </a-descriptions-item>
                    </a-descriptions>
                  </a-col>
                </a-row>
                <div class="text-title">条款内容</div>
                <a-card
                  class="inner-card mt-10"
                  :bordered="false"
                  v-for="(item, index) of clause.multiple_clause"
                  :key="index"
                >
                  <a-descriptions
                    layout="vertical"
                    :labelStyle="labelStyle"
                    :contentStyle="contentStyle"
                    :column="descCols"
                  >
                    <a-descriptions-item
                      label="计租方式"
                      v-if="clause.attribute == 'lease'"
                    >
                      {{ item.compute_lease_unit }}
                    </a-descriptions-item>
                    <a-descriptions-item label="开始时间">
                      {{ item.charge_begintime }}
                    </a-descriptions-item>
                    <a-descriptions-item label="结束时间">
                      {{ item.charge_endtime }}
                    </a-descriptions-item>
                    <a-descriptions-item label="付款时间">
                      {{ item.payment_time_unit1_txt }}
                      {{
                        item.payment_time_unit1 == "unit_3"
                            ? " " + item.payment_time
                            : item.payment_time
                      }}
                      {{
                        item.payment_time_unit2_txt
                            ? "（" + item.payment_time_unit2_txt + "）"
                            : item.payment_time_unit1 == "unit_3"
                                ? "日"
                                : ""
                      }}
                    </a-descriptions-item>
                    <a-descriptions-item label="合同单价">
                      {{
                        item.contract_unit_price + item.contract_price_unit_txt
                      }}
                    </a-descriptions-item>
                    <a-descriptions-item>
                      <template #label>
                        <span>计费类型</span>
                        <text-tip
                          :tips="[
                          '天平均是指单价最后都换算为天单价计算；月平均：指整月的时间段租金单价按月单价计算，不足整月的按换算的天单价计算。月单价=日单价*年天数/12，天单价=月单价*12/年天数。',
                        ]"
                        />
                      </template>
                      {{ item.charge_type_txt || "--" }}
                    </a-descriptions-item>
                    <a-descriptions-item>
                      <template #label>
                        <span>租期划分方式</span>
                        <text-tip
                          :tips="[
                          '按起始日划分',
                          '次月按自然月划分(仅一月一付有效)',
                          '按自然月划分(首月非整自然月划入第一期)',
                          '按自然月划分(首月非整自然月算一个月)',
                        ]"
                        />
                      </template>
                      {{ item.lease_divide_txt || "--" }}
                    </a-descriptions-item>
                    <a-descriptions-item>
                      <template #label>
                        <span>天单价换算规则</span>
                        <text-tip
                          :tips="[
                          '天单价换算规则：按年换算：天单价=月单价*12/年天数',
                          '按自然月换算：天单价=月单价/自然月的天数',
                        ]"
                        />
                      </template>
                      {{ item.convert_day_price_txt || "--" }}
                    </a-descriptions-item>
                    <a-descriptions-item>
                      <template #label>
                        <span>年天数</span>
                        <text-tip :tips="['一年按多少天计算']" />
                      </template>
                      {{ item.year_days }}
                    </a-descriptions-item>
                    <a-descriptions-item label="付款周期">
                      {{ item.payCycle }}月一付
                    </a-descriptions-item>
                    <a-descriptions-item
                      label="区间闭合方式"
                      v-if="
                      item?.divide_mode_unit && item.divide_mode_unit != 'unit1'
                    "
                    >
                      {{ item.section_mode_unit_txt }}
                    </a-descriptions-item>
                  </a-descriptions>
                  <a-descriptions
                    layout="vertical"
                    :labelStyle="labelStyle"
                    :contentStyle="contentStyle"
                    size="small"
                    :column="1"
                    v-if="item?.divide_mode && item?.divide_mode?.length"
                  >
                    <a-descriptions-item
                      :label="item.divide_mode_unit_txt + '分成'"
                    >
                      <div class="w-100p">
                        <a-row :gutter="24" class="divide-row col-header">
                          <a-col :span="6">
                            营业额大于
                            {{ item.section_mode_unit == "unit2" ? "等于" : "" }}
                          </a-col>
                          <a-col :span="6">
                            营业额小于
                            {{ item.section_mode_unit == "unit1" ? "等于" : "" }}
                          </a-col>
                          <a-col :span="6">分成比例</a-col>
                        </a-row>
                        <a-row
                          :gutter="24"
                          class="divide-row"
                          v-for="(divideItem, divideIndex) of item.divide_mode"
                          :key="divideIndex"
                        >
                          <a-col :span="6">{{ divideItem.minPrice }}</a-col>
                          <a-col :span="6">
                            {{
                              divideItem.maxPrice == -1
                                  ? "∞"
                                  : divideItem.maxPrice
                            }}
                          </a-col>
                          <a-col :span="6">{{ divideItem.ratio }}%</a-col>
                        </a-row>
                      </div>
                    </a-descriptions-item>
                  </a-descriptions>
                </a-card>
              </a-card-grid>
            </a-card>
          </section>
          <section
            id="approvalCurrentStep"
            class="mt-20"
            v-if="
            approvalDetail.approveProcess &&
            approvalDetail.approveProcess.length
          "
          >
            <a-card title="当前审批流程">
              <approval-node :list="approvalDetail.approveProcess" />
            </a-card>
          </section>
          <section id="approvalHistory" class="mt-20">
            <a-card title="历史审批流程" class="history">
              <a-collapse
                :bordered="false"
                v-if="
                approvalDetail.approveHistoryProcess &&
                approvalDetail.approveHistoryProcess.length
              "
              >
                <template #expandIcon="{ isActive }">
                  <caret-right-outlined :rotate="isActive ? 90 : 0" />
                </template>
                <a-collapse-panel
                  v-for="item of approvalDetail.approveHistoryProcess"
                  :key="item.approveReason.id"
                >
                  <template #header>
                    <div class="history-header">
                      <div class="title">
                        {{
                          historyStatusMap[item.approveReason.reason_status].text
                        }}
                      </div>
                      <div class="tip">
                      <span v-if="item.approveReason.approve_time">{{
                          item.approveReason.approve_time
                        }}</span>
                        <span v-if="item.approveReason.remark" class="ml-10">
                        备注：{{ item.approveReason.remark }}
                      </span>
                      </div>
                      <div class="tag">
                        <cu-icon
                          type="org-yitongguo"
                          v-if="item.approveReason.reason_status == 1"
                          class="success"
                        />
                        <cu-icon
                          type="org-yijujue"
                          v-if="item.approveReason.reason_status == 2"
                          class="fail"
                        />
                      </div>
                    </div>
                  </template>
                  <approval-node :list="item.approveProcessInfo" />
                </a-collapse-panel>
              </a-collapse>
              <a-empty v-else description="暂无历史审批" />
            </a-card>
          </section>
        </div>
        <section
          v-if="contractDetail.status == 5 ||contractDetail.status == 6 ||contractDetail.status == 7"
          class="footer-header"
          id="footer"
        >
          <a-page-header
            class="demo-page-header"
            style="border: 1px solid rgb(235, 237, 240); background: #fff"
            title=""
            sub-title=""
          >
            <div
              style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
            >
              <div style="display: flex; align-items: center">
                <InfoCircleFilled style="font-size: 16px; color: #2681f3" />
                <div class="total-box" style="margin-left: 10px">
                  <div class="total-item">
                <span class="total-title">合计应收：</span
                ><span class="total-num">{{
                      Math.abs(positiveTotal).toFixed(2)
                    }}</span
                  >元
                  </div>
                  <div class="total-item">
                <span class="total-title">合计应付：</span
                ><span class="total-num">{{
                      Math.abs(negativeTotal).toFixed(2)
                    }}</span
                  >元
                  </div>
                </div>
              </div>
            </div>
          </a-page-header>
        </section>
      </section>
    </section>

    <template v-if="errMsg">
      <div
        style="
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          background-color: #fff;
        "
      >
        <img
          :src="$utils.staticPath + 'images/contract/contract_not_found.jpg'"
          alt=""
          style="width: 300px; height: 300px"
        />
        <span style="font-size: 16px; margin-bottom: 20px">
          {{ errMsg }}
        </span>
      </div>
    </template>
    <!-- 备注弹窗 -->
    <a-modal
      v-model:visible="showRemarkInput"
      title="审批意见"
      @ok="handleRemarkSubmit"
      :centered="true"
    >
      <a-textarea
        v-model:value="remarkValue"
        placeholder="请输入审批意见..."
        :auto-size="{ minRows: 6 }"
      />
      <a-row
        class="mt-10"
        v-if="fileShowList.length"
        :gutter="8"
        align="middle"
      >
        <template v-for="(file, index) of fileShowList" :key="index">
          <a-col :span="20">
            <div class="no-wrap">
              <span style="margin-right: 4px"> {{ index + 1 }}. </span>
              <span class="text-primary">
                {{ file.name }}
              </span>
            </div>
          </a-col>
          <a-col :span="4" class="text-right">
            <a-button type="link" danger @click="removeFile(index)">
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>
          </a-col>
        </template>
      </a-row>
      <div class="mt-10">
        <a-space>
          <!-- :before-upload="(file) => beforeUpload('image', file)" -->
          <a-upload
            v-model:file-list="imgList"
            :multiple="true"
            accept="image/*,.bmp,.tiff"
            :showUploadList="false"
            :action="$utils.fileAction"
            :headers="{ 'org-token': $store.getters.token }"
            :data="{ dir: 'org_contract_approval_image' }"
            @change="handleUploadChange"
          >
            <a-button>
              <template #icon>
                <PictureOutlined />
              </template>
            </a-button>
          </a-upload>
          <a-upload
            v-model:file-list="fileList"
            :multiple="true"
            accept=".doc,.docx,.pdf"
            :showUploadList="false"
            :action="$utils.fileAction"
            :headers="{ 'org-token': $store.getters.token }"
            :data="{ dir: 'org_contract_approval_file' }"
            @change="handleUploadChange"
          >
            <a-button>
              <template #icon>
                <PaperClipOutlined />
              </template>
            </a-button>
          </a-upload>
        </a-space>
      </div>
    </a-modal>

    <RoomDrawer
      :visible="rVisible"
      :detail="rDetail"
      @cancel="rVisible = false"
    />
    <UserDetail
      @request="$utils.commonRequest"
      :visible="userVisible"
      :uid="userId"
      :coordinateData="coordinateData"
      @cancel="userVisible = false"
    />

    <!--  合同详情  -->
    <ContractDetailDrawer
      :visible="contractDetailVisible"
      :id="contractDetailId"
      @handleCancel="
        () => {
          contractDetailVisible = false;
        }
      "
    />

    <!--  结转明细  -->
    <CarryOverMoreDetail
      :visible="carryDetailVisible"
      :id="billDetailId"
      @handleCancel="carryDetailVisible = false"
    />

    <!-- 账单详情 -->
    <BillDetailDrawer
      :visible="billDetailVisible"
      :id="billDetailId"
      @cancel="
        () => {
          billDetailVisible = false;
        }
      "
    />

    <!--  罚没记录  -->
    <ForfeitRecordDrawer
      viewType="view"
      :visible="forfeitRecordVisible"
      :recordList="forfeitRecordInfo?.confiscations || []"
      @handleClose="forfeitRecordVisible = false"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  ref,
  toRefs,
  defineAsyncComponent,
  computed,
} from "vue";
import {
  CaretRightOutlined,
  PictureOutlined,
  PaperClipOutlined,
  DeleteOutlined,
  InfoCircleFilled,
} from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import request from "../../../common/utils/request";
import AttachmentInfo from "../../../components/contract/AttachmentInfo/index.vue";
import ApprovalNode from "./modules/ApprovalNode.vue";
import utils from "../../../common/utils/utils";
import { message } from "ant-design-vue";
import store from "../../../store";
import moment from "moment";
import { TextTip, UserDetail } from "bl-common-vue3";
import RoomDrawer from "../../../components/village/RoomDrawer.vue";
import CarryOverMoreDetail from "@/views/bill/NewRetreat/modules/CarryOverMoreDetail.vue";
import ForfeitRecordDrawer from "@/views/bill/NewRetreat/modules/ForfeitRecordDrawer.vue";
const ContractDetailDrawer = defineAsyncComponent(() =>
  import("@/views/contract/ContractDetail/ContractDetailDrawer.vue")
);
const BillDetailDrawer = defineAsyncComponent(() =>
  import("@/views/bill/BillDetail/modules/BillDetailDrawer.vue")
);

let fromPath = "";

export default defineComponent({
  name: "contractApproval",
  components: {
    InfoCircleFilled,
    ForfeitRecordDrawer,
    CarryOverMoreDetail,
    AttachmentInfo,
    ApprovalNode,
    DeleteOutlined,
    CaretRightOutlined,
    TextTip,
    PictureOutlined,
    PaperClipOutlined,
    RoomDrawer,
    UserDetail,
    ContractDetailDrawer,
    BillDetailDrawer,
  },
  setup() {
    const $route = useRoute();
    const $router = useRouter();
    const contentRef = ref();
    const state = reactive({
      userVisible: false,
      userId: 0,
      coordinateData: {},
      errMsg: "",
      contractDetailVisible: false,
      contractDetailId: 0,
      billDetailId: 0,
      carryDetailVisible: false,
      billDetailVisible: false,
      billTotal: 0, // 账单结算总计
      bondTotal: 0, // 保证金总计
      prestoreTotal: 0, // 预存费用总计
      forfeitRecordInfo: {},
      forfeitRecordVisible: false,
      prestoreData: [],
      purposeData: [],
      purposeLoading: false,
      purposeTotal: 0,
    });
    const notBack = $route.query.noBack;

    // 监听返回按钮显示隐藏
    const isMobile = computed(() => store.getters.isMobile);

    // 合同id
    const contractId = Number($route.query.contractId);
    // 项目审核id
    const approveId = Number($route.query.approveId);

    const isCanceled = ref(false);

    const contractNotFound = ref(false); //合同未找到/不存在


    const getPurposeData = () => {
      if (!contractDetail.value?.id) return;
      state.purposeLoading = true;
      request
        .get("/org", "/contract/change/getPurposseBill", {
          contract_id: contractDetail.value.id,
        })
        .then((res) => {
          // 需付金额
          (res?.bill_info || []).map((item) => {
            item.actual_retreat = utils.countSum([Number(item.actual_payment), Number(item.into_amount || 0), -Number(item.out_amount || 0)]); //  需付金额 = 实收金额 + 转入金额 - 转出金额
            item.actual_retreat = Number(item.actual_retreat).toFixed(2);
            item.return_date = item.return_date || moment().format("YYYY-MM-DD");
          })
          state.purposeData = res?.bill_info || [];
          state.purposeTotal = state.purposeData.reduce((acc, cur) => utils.countSum([acc, Number(cur.actual_retreat)]), 0);
        }).finally(() => {
        state.purposeLoading = false;
      });
    };

    // 获取审核基本内容
    const contractDetail = ref({});
    const attachParams = ref({});
    const getAttach = ref(false);
    const getContractDetail = () => {
      let id = contractId;
      // 如果是变更合同审批，则读取新合同信息
      if (
        approvalDetail.value.mainInfo &&
        approvalDetail.value.mainInfo.process_type &&
        approvalDetail.value.mainInfo.process_type == "change" &&
        approvalDetail.value.mainInfo.change_data &&
        approvalDetail.value.mainInfo.change_data.contract_id
      ) {
        id = approvalDetail.value.mainInfo.change_data.contract_id;
      }
      request
        .get("/org", "/create/contractInfo", { id })
        .then((res) => {
          contractDetail.value = res;
          if (res.status == 8 || res.status == 8 || res.status == 12) {
            // 作废合同
            isCanceled.value = true;
            getContractCancelInfo();
          }
          if (contractDetail.value?.op_type == 5) {
            getPurposeData();
          }
          attachParams.value = {
            contract_id: res.id,
            object_id: res.object_id,
          };
          getAttach.value = true;
          getBuildingInfo();
          if (res.status == 5) {
            request
              .get("/org", "/contract/retreatInfo", {
                contract_id: id,
              })
              .then((res) => {});
          }
        })
        .catch((err) => {
          if (err.code == 10028) {
            contractDetail.value = {};
            contractNotFound.value = true;
          }
        });
    };
    const buildingInfo = ref({});
    const getBuildingInfo = () => {
      const { build_bind } = contractDetail.value;
      const roomNo = build_bind.room.map(
        (item) =>
          `${utils.getBuildNameByBuildBind(item, build_bind)}-${
            item.layer_name
          }-${item.room_name}`
      );
      buildingInfo.value = {
        roomNo: roomNo.join("、"),
        roomNoArr: roomNo,
      };
    };

    const rVisible = ref(false);
    const rDetail = ref({});
    const roomDetail = (checkedBuild) => {
      checkedBuild = checkedBuild || contractDetail.value.build_bind;
      if (
        buildingInfo.value.roomNoArr &&
        buildingInfo.value.roomNoArr.length == 1
      ) {
        rDetail.value = checkedBuild.room[0];
        if (rDetail.value.extra) {
          rDetail.value.village_id = rDetail.value.extra.village_id;
        }
        if (!rDetail.value.village_id) {
          rDetail.value.village_id = checkedBuild.village.id;
        }
        rVisible.value = true;
      }
    };
    // 作废信息
    const cancelInfo = ref({});
    const getContractCancelInfo = () => {
      let id = contractId;
      // 如果是变更合同审批，则读取新合同信息
      if (
        approvalDetail.value.mainInfo &&
        approvalDetail.value.mainInfo.process_type &&
        approvalDetail.value.mainInfo.process_type == "change" &&
        approvalDetail.value.mainInfo.change_data &&
        approvalDetail.value.mainInfo.change_data.contract_id
      ) {
        id = approvalDetail.value.mainInfo.change_data.contract_id;
      }
      request
        .get("/org", "/create/getContractVoid", {
          contract_id: id,
        })
        .then((res) => {
          cancelInfo.value = res.data;
        });
    };

    // 获取审核基本信息
    const approvalDetail = ref({});
    const headerInfo = ref({});
    const retreatInfo = ref({});
    const getApprovalDetail = () => {
      request
        .get("/org", "/contract/approveDetail", {
          id: approveId,
        })
        .then((res) => {
          approvalDetail.value = res.data;
          retreatInfo.value = res.data.mainInfo.content_data;
          const { mainInfo, operateButton, clauseData, historyContractData } =
            res.data;
          if (mainInfo) {
            headerInfo.value = {
              title: mainInfo.process_type_txt,
              statusTxt: mainInfo.status_txt,
              statusColor: headerStatusColorMap[mainInfo.status],
              btns: operateButton,
            };
          }
          if (historyContractData) {
            if (!historyContractData.owner_name) {
              historyContractData.owner_name =
                historyContractData.owner_info.owner_name;
            }
            //保持相同的数据结构
            if (clauseData) {
              historyContractData.clauseData = clauseData;
            }
            contractDetail.value = historyContractData;
            if (contractDetail.value?.op_type == 5) {
              getPurposeData();
            }
            getBuildingInfo();
          } else {
            getContractDetail();
          }
          getRetreatLog();
        })
        .catch((err) => {
          state.errMsg = err?.msg || "";
        });
    };

    let params = {};
    // 顶部按钮点击
    const topBtnClick = (type) => {
      // 查看原合同
      if (type == "LOOK_ORIGINAL") {
        $router.push({
          name: "contractDetail",
          query: {
            id: approvalDetail.value.mainInfo.change_data.original_id,
          },
        });
        return;
      }
      // 查看新合同
      if (type == "LOOK_NEW") {
        $router.push({
          name: "contractDetail",
          query: {
            id: approvalDetail.value.mainInfo.change_data.contract_id,
          },
        });
        return;
      }
      if (btnTypeMap[type].status == 5) {
        // 再次申请
        params = {
          contract_id: approvalDetail.value.mainInfo.contract_id,
          type: approvalDetail.value.mainInfo.process_type,
          needMsg: true,
        };
        request.post("/org", "/contract/launchApprove", params).then((res) => {
          // 更新合同列表
          store.dispatch("SetContractListUpdate", true).then(() => {
            message.success(res.msg || "操作成功！");
            goBack();
          });
        });
      } else {
        params = {
          id: approveId,
          status: btnTypeMap[type].status,
        };
        if (btnTypeMap[type].remark) {
          showRemarkInput.value = true;
        } else {
          utils.modalConfirm({
            content: btnTypeMap[type].content,
            onOk: () => {
              handleApprovalSubmit();
            },
          });
        }
      }
    };

    // 审批上传
    const imgList = ref([]);
    const fileList = ref([]);
    const fileShowList = ref([]);
    const handleUploadChange = (info) => {
      // console.log("handleUploadChange info", info);
      const { file } = info;
      if (file && file.response && file.status == "done") {
        if (file.response.code == 1000) {
          // 上传成功
          fileShowList.value.push({
            name: file.name,
            url: file.response.data.fileUrl,
          });
        } else {
          // 上传失败
          message.warning(`文件“${file.name}”上传失败！`);
        }
      }
    };
    const removeFile = (index) => {
      fileShowList.value.splice(index, 1);
    };

    // 审批操作
    const handleApprovalSubmit = () => {
      request
        .put("/org", "/contract/makeApprove", { ...params, needMsg: true })
        .then((res) => {
          message.success(res.msg || "操作成功");
          fileShowList.value = [];
          fileList.value = [];
          imgList.value = [];
          // 更新合同列表
          store.dispatch("SetContractListUpdate", true).then(() => {
            // 如果是意向合同，作废后直接到意向合同列表
            if (contractDetail.value.op_type == 5) {
              $router.push({
                name: "purposeContractList",
                query: {},
              });
            } else {
              getApprovalDetail();
            }
          });
        });
    };

    // 提交审批备注
    const remarkValue = ref("");
    const showRemarkInput = ref(false);
    const handleRemarkSubmit = () => {
      showRemarkInput.value = false;
      params.remark = remarkValue.value;
      params.remark_files = fileShowList.value;
      remarkValue.value = "";
      handleApprovalSubmit();
    };

    const billTableData = ref([]);
    const bondTableData = ref([]);

    // positive 需收 total
    const positiveTotal = computed(() => {
      let tmpTotal = 0;
      if (state.billTotal > 0) {
        tmpTotal = utils.countSum([tmpTotal, state.billTotal])
      }
      if (state.bondTotal > 0) {
        tmpTotal = utils.countSum([tmpTotal, state.bondTotal])
      }
      return tmpTotal;
    });

    // negative 需付 total
    const negativeTotal = computed(() => {
      let tmpTotal = 0;
      if (state.billTotal < 0) {
        tmpTotal = utils.countSum([tmpTotal, state.billTotal])
      }
      if (state.bondTotal < 0) {
        tmpTotal = utils.countSum([tmpTotal, state.bondTotal])
      }
      if (state.prestoreTotal < 0) {
        tmpTotal = utils.countSum([tmpTotal, state.prestoreTotal])
      }
      return tmpTotal;
    });

    const billTotalStatus = computed(() => {
      if (state.billTotal >= 0) {
        return "合计需收：";
      } else {
        return "合计需付：";
      }
    });
    const handleBillData = (sourceData) => {
      // 同步处理数据
      let tmpTotal = 0;
      (sourceData || []).forEach((item) => {
        let actualAmount = utils.countSum([
          Number(item.actual_payment),
          Number(item.into_amount),
          -Number(item?.out_amount || 0),
        ]);
        let amount = utils.countSum([
          Number(item.receivable_payment),
          -Number(actualAmount),
        ]);
        if (item.id) {
          item.actual_retreat = Math.abs(amount).toFixed(2);
          if (
            amount >=
            0
          ) {
            item.pay_type = 'income';
          } else {
            item.pay_type = 'pay';
          }
        } else {
          // 自己添加的收款||付款单
          if (item.bill_type == 2) {  // 兼容老数据
            item.pay_type = "pay";
          } else {
            item.pay_type = "income";
          }
          if (item.pay_type == 'pay' && amount >= 0) {
            amount = utils.countSum([
              0,
              -Number(amount),
            ]);
          }
        }
        tmpTotal = utils.countSum([tmpTotal, amount, Number(item.need_latefee)]);
      })
      state.billTotal = tmpTotal;
      return sourceData;
    };

    const bondTotalStatus = computed(() => {
      if (state.bondTotal > 0) {
        return "合计需收：";
      } else {
        return "合计需付：";
      }
    });
    const handleBondData = (sourceData) => {
      let tmpTotal = 0;
      (sourceData || []).forEach((item) => {
        tmpTotal = utils.countSum([tmpTotal, -Number(item.receivable_payment), Number(item.need_latefee)]);
      })
      state.bondTotal = tmpTotal;
      return sourceData;
    };

    const handlePrestoreData = (sourceData) => {
      let tmpTotal = 0;
      (sourceData || []).forEach((item) => {
        let tmp = 0;
        tmp = Number(item.actual_retreat);
        if (
          item.bill_type == 2
        ) {
          tmp = 0 - tmp;
        }
        tmpTotal = utils.countSum([tmpTotal, tmp]);
      })
      state.prestoreTotal = tmpTotal;
      return sourceData;
    };
    const getRetreatLog = () => {
      let id = contractId;
      // 如果是变更合同审批，则读取新合同信息
      if (
        approvalDetail.value.mainInfo &&
        approvalDetail.value.mainInfo.process_type &&
        approvalDetail.value.mainInfo.process_type == "change" &&
        approvalDetail.value.mainInfo.change_data &&
        approvalDetail.value.mainInfo.change_data.contract_id
      ) {
        id = approvalDetail.value.mainInfo.change_data.contract_id;
      }
      request
        .get("/org", "/contract/getRetreatLog", {
          contract_id: id,
        })
        .then((res) => {
          billTableData.value = handleBillData(res?.retreatData?.bill_info);
          bondTableData.value = handleBondData(res?.retreatData?.bond_info);
          state.prestoreData = handlePrestoreData(res?.retreatData?.prestore_info);
        });
    };
    // 跳转合同详情
    const checkContractDetail = () => {
      let id = contractId;
      // 如果是变更合同审批，则读取新合同信息
      if (
        approvalDetail.value.mainInfo &&
        approvalDetail.value.mainInfo.process_type &&
        approvalDetail.value.mainInfo.process_type == "change" &&
        approvalDetail.value.mainInfo.change_data &&
        approvalDetail.value.mainInfo.change_data.contract_id
      ) {
        id = approvalDetail.value.mainInfo.change_data.contract_id;
      }

      state.contractDetailId = id;
      if (isMobile.value) {
        $router.push({
          name: "contractDetail",
          query: {
            id
          },
        });
      } else {
        state.contractDetailVisible = true;
      }
    };

    const init = () => {
      getApprovalDetail();
    };
    init();

    const goBack = () => {
      if (fromPath == "/") {
        $router.replace("/index");
      } else {
        $router.back();
      }
    };

    const dateFormat = (date) => {
      if (date) {
        return moment(date).format("YYYY-MM-DD");
      } else {
        return "-";
      }
    };

    const billColumns = [
      {
        title: "账单编号",
        dataIndex: "bill_number",
        key: "bill_number",
        width: 200,
        fixed: "left",
      },
      {
        title: "费用类型",
        dataIndex: "cost_type_txt",
        key: "cost_type_txt",
        width: 160,
      },
      {
        title: "计费周期",
        customRender: ({ text, record, index }) => {
          return record.start_date + " ~ " + record.end_date;
        },
        width: 200,
      },
      {
        title: "账单金额",
        dataIndex: "bill_amount",
        width: 160,
      },
      {
        title: "滞纳金",
        dataIndex: "need_latefee",
        key: "need_latefee",
        width: 160,
        customRender: ({ text, record, index }) => {
          return text || "--";
        },
      },
      {
        title: "结转",
        dataIndex: "carry_over",
        key: "carry_over",
        width: 220,
      },
      {
        title: "需收/付金额",
        dataIndex: "actual_retreat",
        key: "actual_retreat",
        width: 200,
      },
      {
        title: "应收/付日期",
        dataIndex: "receivable_payment_date",
        width: 180,
        fixed: "right",
      },
    ];

    const bondColumns = [
      {
        title: "账单编号",
        dataIndex: "bill_number",
        key: "bill_number",
        fixed: "left",
        width: 200,
      },
      {
        title: "费用类型",
        dataIndex: "cost_type_txt",
        width: 140,
      },
      {
        title: "计费周期",
        customRender: ({ text, record, index }) => {
          return record.start_date + " ~ " + record.end_date;
        },
        width: 200,
      },
      {
        title: "账单金额",
        dataIndex: "bill_amount",
        width: 160,
      },
      {
        title: "滞纳金",
        dataIndex: "need_latefee",
        key: "need_latefee",
        width: 140,
      },
      {
        title: "实收金额",
        dataIndex: "actual_payment",
        width: 140,
      },
      {
        title: "结转",
        dataIndex: "carry_over",
        key: "carry_over",
        width: 200,
      },
      {
        title: "罚没",
        dataIndex: "forfeit_amount",
        key: "forfeit_amount",
        width: 160,
      },
      {
        title: "需付金额",
        dataIndex: "receivable_payment",
        width: 140,
      },
      {
        title: "应付日期",
        dataIndex: "receivable_payment_date",
        key: "receivable_payment_date",
        width: 180,
      },
    ];

    // 获取条款所选房源
    const getClauseCheckedBuild = (list) => {
      const nameList = list.room.map(
        (item) =>
          `${ utils.getBuildNameByBuildBind(item, list)
          }-${item.layer_name}-${item.room_name}`
      );
      return nameList.join("，");
    };

    const showUserInfo = (info, field) => {
      if (!info[field]) {
        return;
      }
      state.userId = info[field];
      state.coordinateData = window.event;
      setTimeout(() => {
        state.userVisible = true;
      }, 50);
    };

    /* 查看结转明细 */
    const viewCarryOver = (record) => {
      state.billDetailId = record.id;
      if (!state.billDetailId) return;
      state.carryDetailVisible = true;
    };

    const viewBillDetail = (id) => {
      state.billDetailId = id;
      if (!state.billDetailId) return;
      state.billDetailVisible = true;
    };

    /* 查看罚没明细 */
    const viewForfeit = (record) => {
      state.forfeitRecordInfo = record;
      state.forfeitRecordVisible = true;
    };

    return {
      ...descStyle,
      historyStatusMap,
      descCols,
      descCols2,
      headerInfo,
      approvalDetail,
      contractDetail,
      buildingInfo,
      getAttach,
      attachParams,
      contentRef,
      showRemarkInput,
      remarkValue,
      cancelInfo,
      isCanceled,
      handleRemarkSubmit,
      goBack,
      topBtnClick,
      isMobile,
      retreatInfo,
      dateFormat,
      billColumns,
      bondColumns,
      billTableData,
      bondTableData,
      checkContractDetail,
      getClauseCheckedBuild,
      imgList,
      fileList,
      fileShowList,
      handleUploadChange,
      removeFile,
      contractNotFound,
      roomDetail,
      rVisible,
      rDetail,
      showUserInfo,
      ...toRefs(state),
      prestoreColumns,
      billTotalStatus,
      bondTotalStatus,
      viewCarryOver,
      viewBillDetail,
      viewForfeit,
      positiveTotal,
      negativeTotal,
      notBack,
      purposeColumns,
    };
  },
  beforeRouteEnter(to, from, next) {
    fromPath = from.path;
    next();
  },
});

const descCols = { xxl: 5, xl: 4, lg: 3, md: 2, xs: 2 };
const descCols2 = { md: 3, sm: 2, xs: 1 };
// 1=待审批(审批中);2=审批通过;3=审批不通过;4=已撤回(关闭申请);
const headerStatusColorMap = {
  1: "orange",
  2: "green",
  3: "red",
  4: "gray",
};
// status: 1=通过;2=拒绝;3=关闭申请;4=关闭申请+删除合同;
const btnTypeMap = {
  PASS: {
    status: 1,
    remark: true,
  },
  REFUSE: {
    status: 2,
    remark: true,
  },
  CLOSE: {
    status: 3,
    content: "确定要关闭申请吗？",
  },
  CLOSE_DEL: {
    status: 4,
    content: "确定要关闭申请并删除合同吗？",
  },
  AGAIN: {
    status: 5,
  },
};
const descStyle = {
  labelStyle: {
    color: "rgba(0,0,0,0.5)",
    fontSize: "12px",
    display: "flex",
    alignItems: "center",
  },
  contentStyle: {
    color: "rgba(0,0,0,0.8)",
    marginBottom: "15px",
    overflow: "hidden",
    paddingRight: "8px",
  },
};

// 历史审核状态
const historyStatusMap = {
  1: {
    text: "审批已通过",
    type: "success",
  },
  2: {
    text: "审批已拒绝",
    type: "fail",
  },
  3: {
    text: "申请已被关闭",
    type: "fail",
  },
  4: {
    text: "申请已被关闭",
    type: "fail",
  },
};

const prestoreColumns = [
  {
    title: "专项预存",
    dataIndex: "cost_name",
    width: "20%",
  },
  {
    title: "预存金额",
    dataIndex: "amount",
    width: "20%",
  },
  {
    title: "剩余金额",
    dataIndex: "nomatch_price",
    width: "20%",
  },
  {
    title: "需付金额",
    dataIndex: "actual_retreat",
    key: "actual_retreat",
    width: "20%",
  },
  {
    title: "应付日期",
    dataIndex: "receivable_payment_date",
    key: "receivable_payment_date",
    width: "20%",
  },
];

const purposeColumns = [
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    key: "cost_type_txt",
    width: "8%",
  },
  {
    title: "计费周期",
    dataIndex: "contractOn",
    key: "contractOn",
    width: "14%",
  },
  {
    title: "账单金额",
    dataIndex: "bill_amount",
    key: "bill_amount",
    width: "14%",
  },
  {
    title: "需付金额",
    dataIndex: "actual_retreat",
    key: "actual_retreat",
    width: "12%",
  },
  {
    title: "实收金额",
    dataIndex: "actual_payment",
    key: "actual_payment",
    width: "12%",
  },
  {
    title: "结转",
    dataIndex: "carry_over",
    key: "carry_over",
    width: "14%",
  },
  {
    title: "应退金额",
    dataIndex: "actual_retreat",
    key: "actual_retreat",
    width: "12%",
  },
  {
    title: "应退日期",
    dataIndex: "return_date",
    key: "return_date",
    width: "14%",
  },
];
</script>

<style lang="less" scoped>
.success {
  color: @success-color;
}
.fail {
  color: @error-color;
}
.contract-approval {
  height: 100%;
  // display: flex;
  // flex-direction: column;
  &.isMobile {
    :deep(.ant-page-header-back) {
      display: none;
    }
    .header {
      height: auto;
      overflow: auto;
    }
    .content {
      height: calc(100% - 50px);
      &.hasHandleBtn {
        height: calc(100% - 90px);
      }
      .right {
        padding: 0px;
      }
    }
  }
  .header {
    background: #fff;
    height: 70px;
    overflow: hidden;
    &:deep(.ant-page-header) {
      padding: 10px 20px 0 20px;
    }
  }
  .content {
    flex: 1;
    width: 100%;
    height: calc(100% - 70px);
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    .left {
      width: 160px;
      padding: 10px;
      flex-shrink: 0;
      &:deep(.ant-anchor-ink::before) {
        background-color: #ccc;
      }
    }
    .right {
      flex: 1;
      min-width: 0;
      display: flex;
      flex-direction: column;
      .right-content {
        overflow-y: auto;
        padding: 0 10px;
      }
      .inner-card {
        padding: 20px 10px 0 10px;
        background: @primary-color-bg;
        .divide-row {
          width: 100%;
          height: 32px;
          line-height: 32px;
          vertical-align: middle;
        }
        .col-header {
          font-weight: bold;
        }
      }
      .history {
        &:deep(.ant-collapse-item) {
          border: none;
        }
        &:deep(.ant-card-body) {
          padding: 20px;
        }
        .history-header {
          position: relative;
          .title {
            line-height: 30px;
            font-weight: bold;
            font-size: 15px;
          }
          .tip {
            color: #999;
            line-height: 24px;
          }
          .tag {
            position: absolute;
            right: 0;
            font-size: 40px;
            top: 50%;
            transform: translateY(-50%);
          }
        }
      }
    }
  }
  .bill-card {
    :deep(.ant-alert-info) {
      background-color: #fafafa;
      border: none;
    }

    :deep(.ant-alert-message) {
      text-align: right;
      padding-right: 10px;
      font-weight: 600;
    }
  }
}
.total-item {
  margin-right: 10px;
}
.total-box {
  display: flex;
  font-weight: bold;
}
.total-num {
  margin: 0 5px;
  font-size: 18px;
  color: @primary-color;
}
.footer-header {
  padding: 2px 10px 0 10px;
  :deep(.ant-list-item-meta-avatar) {
    margin-right: 32px;
    margin-left: 16px;
    margin-top: 10px;
  }

  :deep(.ant-page-header) {
    padding-bottom: 0;
  }
}
#footer {
  :deep(.ant-page-header) {
    padding-bottom: 20px;
  }
}
.hide-back {
  :deep(.ant-page-header-back) {
    display: none;
  }
}
</style>
